<?php

namespace App\Http\Controllers\Api;

use App\Model\Position;
use App\Model\User;
use Illuminate\Http\Request;
use App\Service\UserService;

use App\Model\Bistro;
use Illuminate\Support\Facades\Redis;
use App\Transformers\UserTransformer;


use App\Transformers\BistroTransformer;

use App\Http\Controllers\Controller;

class BistroController extends Controller
{
    //

    public function index() {
        $bistros = Bistro::paginate(10);
        $data['data'] = [
            'bistros' => $this->factalPaginator($bistros, new BistroTransformer())
        ];
        return $this->apiSuccess($data);
    }

    public function findBistroByQrcode(Request $request) {
        $qr_code = $request->input('qr_code');//座位id
        $position = Position::where('qr_code', $qr_code)->first();

        $bistro = Bistro::findorfail($position->bistro_id);

        $data = [
            'bistro' => $bistro
        ];
        return $this->apiSuccess($data);
    }


    public function nowDinner(Request $request) {//当前桌的请客
        $return_data = UserService::getUser($request->header('AuthrizeOpenId'));
        if($return_data['errcode'] > 0) return $this->apiError($return_data['errmsg']);
        $user = $return_data['data'];
        $qr_code = $request->input('qr_code');
        $position = Position::where('qr_code', $qr_code)->first();
        if(empty($position)) return $this->apiError('该位置不存在');

        $now_open_id_s_str = Redis::get('orderdinner:position_id||'.$position->id);
        if(empty($now_open_id_s_str)) {
            $now_open_id_s = [];
        }else{
            $now_open_id_s = json_decode($now_open_id_s_str, true);
        }
        $data['data'] = [];

        if(!empty($now_open_id_s)) {
            foreach ($now_open_id_s as $now_open_id) {
//            if(empty($now_open_id)) return $this->apiError('暂无请客单');
                $master = User::where('open_id', $now_open_id)->first();
                array_push($data['data'], [
                    'master_open_id' => $now_open_id,
                    'msater' => $this->fractalItem($master, new UserTransformer()),
                    'password' => Redis::get('orderdinner:position_id||'.$position->id.'||openid||'.$request->header('AuthrizeOpenId').'password')//记录哪个崽种请客
                ]);
            }
        }

        return $this->apiSuccess($data);
    }

}
